import React, { useState } from 'react';
import { Breadcrumb, Button, Card, Input, Radio, Table, Image, Modal, Form, notification, Popconfirm, Upload, DatePicker } from 'antd';
import { RedoOutlined, MoreOutlined, DeleteOutlined, AudioOutlined, UploadOutlined, PlusCircleOutlined, CloudDownloadOutlined } from '@ant-design/icons';
import '../../style/healthymanage.scss'
import axios from 'axios';
import { useEffect } from 'react';
import { useHealth } from '../../hooks/tripmanage'
import { useForm } from 'antd/es/form/Form';
import { useNavigate } from 'react-router-dom';
import { del_hlist, search_hlist, health_list, search_hlist2 } from '../../utils/api2'


//表格组件
const suffix = (
  <AudioOutlined
    style={{
      fontSize: 16,
      color: '#1890ff',
    }}
  />
);
function Healthymange(props) {
  //调用钩子函数获取表格数据
  var [list, setList] = useHealth()
  //在初始挂载期发送分页请求
  useEffect(() => {
    health_list().then((res) => {
      setList(res.data)
      setpaination({ current: pagination.current, pageSize: 5, total: res.data.length })
    })
  }, [])
  //导入文件

  //定义文件状态
  var [filestatus, setStatus] = useState('')
  var [file, setFile] = useState([])
  const prop = {
    action: 'upload',
    onChange({ file, fileList }) {
      if (file.status !== 'uploading') {
        console.log(file, fileList);
        setFile(fileList)
      }

      if (file.status == 'error') {
        file.status = 'done'
        setStatus(file.status)
      }
    }
  }
  const columns = [
    {
      title: '学号',
      dataIndex: 'con',
    },
    {
      title: '学生姓名',
      dataIndex: 'name',
      render: (text) => <a>{text}</a>,
    },
    {
      title: '监测时间',
      dataIndex: 'Jtime',
    },
    {
      title: '体温',
      dataIndex: 'temperature',
    },
    {
      title: '体检报告',
      render: () => (
        <>
          <Upload {...prop} accept='.doc,.docx' action={localStorage.setItem('file', JSON.stringify(file))}>
            <Button icon={<UploadOutlined />}>上传健康报告</Button>
          </Upload>
        </>
      )

    },
    {
      title: '检测状态',
      render: (record) => (
        <>
          {
            record.status == true ?
              <Button type='primary' onClick={() => { Fchange(record) }}>正常</Button>
              :
              <Button type="primary" danger onClick={() => { Tchange(record) }}>危险</Button>

          }
        </>
      )
    },
    {
      title: '上传时间',
      dataIndex: 'Utime',
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record, key) => (
        <>
          <MoreOutlined className='edit' onClick={() => { More(record) }} />
          <DeleteOutlined className='del' onClick={() => { del(record) }} />
          {/* {
                    filestatus != 'done' ?
                    <></>
                    :
                    <CloudDownloadOutlined className='down' />
                  } */}
        </>
      )
    }

  ];

  const config = {
    rules: [
      {
        type: 'object',
        required: true,
        message: '请输入日期',
      },
    ],
  };
  //更变按钮状态的点击事件
  var Fchange = (record) => {
    axios.patch(`/health/${record.id}`, { status: false }).then((res) => {
      console.log(res.data);
      notification.warning({ message: '该生状态已改为危险' })
    })
    health_list().then((res) => {
      setList(res.data)
    })

  }
  var Tchange = (record) => {
    axios.patch(`/health/${record.id}`, { status: true }).then((res) => {
      notification.info({ message: '该生状态已改为正常' })
      console.log(res.data);
    })
    health_list().then((res) => {
      setList(res.data)
    })
  }
  // 更多操作按钮
  var [params, setParams] = useState([])
  var More = (record) => {
    setParams(record)
    showModal()

  }
  //表单提交按钮
  // 创建form实例
  const [form] = Form.useForm()
  var [values, setValue] = useState({})
  const onFinish = (values) => {
    console.log(values);
    setValue(values)
    axios.patch(`/health/${params.id}`, { name: values.name, con: values.con, temperature: values.temperature, Jtime: time.$y + '-' + (time.$M + 1) + '-' + time.$D, Utime: time2.$y + '-' + (time2.$M + 1) + '-' + time2.$D + ' ' + time2.$H + ' : ' + time2.$m }).then((res) => {
      console.log(res.data);
    })
    notification.success({ message: "健康管理信息已修改" })
    health_list().then((res) => {
      setList(res.data)
    })

  };
  // 对话框
  const [isModalOpen, setIsModalOpen] = useState(false);
  const showModal = () => {
    setIsModalOpen(true);

  };
  const handleOk = () => {
    console.log(values);
    setIsModalOpen(false)
    form.submit()

    // 使用submit调用onFinish函数
  };
  const handleCancel = () => {
    setIsModalOpen(false)
    form.resetFields();

  };
  //删除
  var del = (record) => {
    del_hlist(record.id).then((res) => {
      console.log(res.data);
    })
    notification.success({ message: "该生信息已删除" })
    health_list().then((res) => {
      setList(res.data)
    })
  }
  //搜索框
  const { Search } = Input;
  var [searchlist, setSearch] = useState([])
  const onSearch = (value) => {
    console.log(value);
    if (value) {
      search_hlist(value).then((res) => {
        if (res.data.length == 0) {
          notification.warning({ message: '查无此用户' })
        }
        setSearch(res.data)
        console.log(res.data);
      })
      health_list().then((res) => {
        setList(res.data)
      })
    } else {
      notification.warning({ message: '搜索内容为空' })
    }

  }
  const onSearch2 = (value) => {
    console.log(value)

    if (value) {
      search_hlist2(value).then((res) => {
        if (res.data.length == 0) {
          notification.warning({ message: '查无此用户' })
        }
        setSearch(res.data)
      })
      health_list().then((res) => {
        setList(res.data)
      })
    } else {
      notification.warning({ message: '搜索内容为空' })
    }
  }

  const [selectionType, setSelectionType] = useState('checkbox');
  var data = searchlist.length == 0 ? list : searchlist
  //复选框
  var [keys, setKeys] = useState([])
  const rowSelection = {
    onChange: (selectedRowKeys, selectedRows) => {
      console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
      setKeys(selectedRowKeys)
    }
  };
  //点击添加按钮跳转页面

  //调用钩子函数
  var navigator = useNavigate()
  var add = () => {
    navigator('/index/healthymangeadd')
  }
  //获取时间数据
  var [time, setTime] = useState([])
  var change = (value) => {
    // console.log(value);
    setTime(value)
  }
  var [time2, setTime2] = useState({})
  var change2 = (value) => {
    // console.log(value);
    setTime2(value)
  }
  //刷新页面
  var update = () => {
    navigator(0)
  }
  //分页
  var [pagination, setpaination] = useState({ current: 1, pageSize: 5, total: 20 })
  const handleChange = (pagination) => {
    setpaination(pagination)
    health_list().then((res) => {
      setList(res.data)
      setpaination({ current: pagination.current, pageSize: 5, total: res.data.length })
    })
  }
  return (
    // 行程管理模块
    <div className='healthmanage'>
      <Breadcrumb>
        <Breadcrumb.Item>
          <a href='/index/home'>
            首页
          </a>
        </Breadcrumb.Item>
        <Breadcrumb.Item>
          <a href="">健康管理</a>
        </Breadcrumb.Item>
        <Breadcrumb.Item>
          <span>健康状况</span>
        </Breadcrumb.Item>
        <Button icon={<RedoOutlined />} className="update" type='primary' onClick={update} />
      </Breadcrumb>
      <div className="Card">
        <Card
          title="健康管理"
          bordered={false}
          className="Child"
          style={{
            width: "100%",

          }}
        >
          {/* 表格数据 */}
          <div>
            <Search
              placeholder="请输入学号"
              onSearch={onSearch}
              style={{
                width: 200,
              }}
              className="input1"
            />
            <Search
              placeholder="请输入学生姓名"
              allowClear
              onSearch={onSearch2}
              style={{
                width: 200,
              }}
              className="input2"
            />
            <Button type="primary" className='add' icon={<PlusCircleOutlined />} onClick={add}></Button>
            <div className='buttonBox'>

              <Button type="primary" disabled={keys.length == 0} >批量删除</Button>
              {/* <Button type="primary" disabled = {keys.length == 0}>批量修改行程</Button> */}
            </div>
            <Modal title="Basic Modal" open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
              <Form
                labelCol={{ span: 6 }}
                wrapperCol={{ span: 18 }}
                onFinish={onFinish}
                // 绑定form实例
                form={form}


              >
                <Form.Item
                  label="学号"
                  name="con"
                  rules={[{ required: true, message: '输入学号' }]}
                  initialValue={params.con}
                >
                  <Input placeholder='输入账号' />
                </Form.Item>

                <Form.Item
                  label="学生姓名"
                  name="name"
                  rules={[{ required: true, message: '输入姓名' }]}
                  initialValue={params.name}
                >
                  <Input placeholder='输入学生姓名' />
                </Form.Item>

                <Form.Item name="datepicker" label="监测时间" {...config} >
                  <DatePicker onChange={change} format="YYYY-MM-DD" picker='date' />
                  {/* <DatePicker  onChange={change}/> */}
                </Form.Item>
                <Form.Item
                  label="体温"
                  name="temperature"
                  rules={[{ required: true, message: '输入体温' }]}
                  initialValue={params.temperature}
                >
                  <Input placeholder='请输入体温' />
                </Form.Item>
                <Form.Item name="datetimepicker" label="上传时间" {...config}>
                  <DatePicker showTime format="YYYY-MM-DD HH:mm:ss" onChange={change2} />
                </Form.Item>

                {/* <Form.Item
                   wrapperCol={{
                     ...layout.wrapperCol,
                     offset: 8,
                   }}
                 >
                   <Button type="primary" htmlType="submit">
                     Submit
                   </Button>
                 </Form.Item> */}
              </Form>
            </Modal>
            <Radio.Group
              onChange={({ target: { value } }) => {
                setSelectionType(value);
              }}
              value={selectionType}
            >
            </Radio.Group>

            <Table
              rowSelection={{
                type: selectionType,
                ...rowSelection,
              }}
              columns={columns}
              dataSource={data}
              pagination={pagination}
              onChange={handleChange}
              size="middle"
            />
          </div>
        </Card>
      </div>
    </div>
  );
}

export default Healthymange;